import React, { useState, useMemo } from 'react';
import { connect } from 'umi';
import { Form, Row, Col, Select, Button, notification, Modal } from 'antd';
import {
  listAllBySiteID, // 根据Site 查询
  getModelList, // 根据感测器类型
  listAllByBuildingID, // 根据建物资讯
  listDeviceListByCondition, // 全部 查询
} from './setServers';
import styles from '@/assets/setting/BuildSet.less';
import SensorSetTable from './SensorSetTable';

const { Option } = Select;
const frequencyData = [
  { time: '10', value: '10' },
  { time: '300', value: '300' },
];

interface SensorSet {
  dvaData: any;
  [key: string]: any;
}

const selectOption = (list: any, valN: string, name: string) => {
  return list.map((item: any) => (
    <Option key={item[valN]} value={item[valN]}>
      {item[name]}
    </Option>
  ));
};

function SensorSet(props: SensorSet) {
  const [sensorSelectForm] = Form.useForm();
  const { dvaData } = props;

  // console.log('BuildSetTable sensorToProps', dvaData);

  const [showBuildType, setShowBuildType] = useState(false);
  const [typeBuildData, setTypeBuildData] = useState([]);
  const [showtypeType, setShowtypeType] = useState(false);
  const [buildTypeData, setBuildTypeData] = useState([]);
  // 全部感测器类型
  const [meterModelData, setMeterModelData] = useState([]);
  // 新增 Modal 的数据
  const [addModalData, setAddModalData] = useState({
    devicetype: '',
    siteId: '',
  });
  // 表格数据
  const [sensorTabD, setSensorTabD] = useState<any>(false);

  /* 根据选择的site 渲染不同的build */
  const getBuildType = (params: any) => {
    listAllBySiteID(params).then((res: any) => {
      // console.log('查询 建物资讯 是否成功', res);
      res && setTypeBuildData(res['data']);
      setShowBuildType(true);
    });
  };
  /* 根据选择的感测器类型 查询全部厂牌类型 */
  const getMeterModelList = (params: any) => {
    getModelList(params).then((res) => {
      console.log('查询到的全部感测器类型', res);
      res && setMeterModelData(res['data']);
    });
  };
  /* 根据选择的建物 渲染不同的区域 */
  const gettypeType = (params: any) => {
    listAllByBuildingID(params).then((res: any) => {
      res && setBuildTypeData(res['data']);
      setShowtypeType(true);
    });
  };
  /* 根据条件查询 */
  const getByCondition = () => {
    sensorSelectForm.validateFields().then((val: any) => {
      console.log('查询后的全部数据！！！', val);
      setAddModalData(val);
      listDeviceListByCondition(val).then((res) => {
        console.log('根据条件查询后的数据', res);
        if (res['data']) {
          setSensorTabD(res['data']);
        }
      });
    });
    // .catch((rej: any) => {
    //   console.log('rej, asjkfklasuoidfjhuidj', rej);
    //   notification.error({
    //     message: '查询结果！',
    //     description: rej.message || '查询失败！',
    //   });
    // });
  };

  /* 表格 */
  const sensorSetTable = useMemo(() => {
    return (
      <SensorSetTable
        getByCondition={getByCondition}
        addModalData={addModalData}
        sensorTabD={sensorTabD}
        typeBuildData={typeBuildData}
        meterModelData={meterModelData}
        facListAll={dvaData['facListAll']}
        deviceTypeListAll={dvaData['deviceTypeListAll']}
        stateTypeListAll={dvaData['stateTypeListAll']}
      />
    );
  }, [sensorTabD]);

  return (
    <>
      <h2>感测器资讯设定</h2>
      <Form
        form={sensorSelectForm}
        name="sensorSelectForm"
        labelCol={{ span: 5 }}
        autoComplete="off"
        initialValues={{
          siteId: '',
          buildingId: '',
          areaId: '',
          readFreq: '',
          status: '',
          deviceType: '',
        }}
      >
        <Row gutter={24}>
          <Col span={10}>
            <Form.Item
              name="siteId"
              label="Site"
              rules={[{ required: true, message: '请选择 Site' }]}
            >
              <Select
                className={styles['select__width']}
                onChange={(val: string) => {
                  // console.log("选择的 Site", val);
                  getBuildType({ siteId: val });
                }}
              >
                {dvaData['facListAll'].length &&
                  selectOption(dvaData['facListAll'], 'siteid', 'ename')}
              </Select>
            </Form.Item>
          </Col>
          <Col span={10}>
            <Form.Item
              name="deviceType"
              label="感测器类型"
              rules={[{ required: true, message: '请选择 感测器类型' }]}
            >
              <Select
                className={styles['select__width']}
                onChange={(val: any) => {
                  console.log('选择的感测器类型', val);
                  getMeterModelList({ dType: val });
                }}
              >
                {dvaData['deviceTypeListAll'].length &&
                  selectOption(dvaData['deviceTypeListAll'], 'id', 'typename')}
              </Select>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={24}>
          <Col span={10}>
            {showBuildType && (
              <Form.Item name="buildingId" label="建物资讯">
                <Select
                  className={styles['select__width']}
                  onChange={(val: string) => {
                    console.log('选择的 建物', val);
                    gettypeType({ buildingId: val });
                  }}
                >
                  {typeBuildData.length &&
                    selectOption(typeBuildData, 'ID', 'NAME')}
                </Select>
              </Form.Item>
            )}
          </Col>
          <Col span={10}>
            {showtypeType && (
              <Form.Item name="areaId" label="区域资讯">
                <Select className={styles['select__width']}>
                  {buildTypeData.length &&
                    selectOption(buildTypeData, 'ID', 'NAME')}
                </Select>
              </Form.Item>
            )}
          </Col>
        </Row>
        <Row gutter={24}>
          <Col span={10}>
            <Form.Item name="readFreq" label="读取频率">
              <Select className={styles['select__width']}>
                {selectOption(frequencyData, 'time', 'value')}
              </Select>
            </Form.Item>
          </Col>
          <Col span={10}>
            <Form.Item name="status" label="感测器状态">
              <Select className={styles['select__width']}>
                {selectOption(dvaData['stateTypeListAll'], 'Code', 'Remark')}
              </Select>
            </Form.Item>
          </Col>
          <Col span={4}>
            <Button type="primary" onClick={getByCondition}>
              查询
            </Button>
          </Col>
        </Row>
      </Form>

      {sensorSetTable}
    </>
  );
}

/* 挂载 到仓库中 */
const sensorToProps = (state: any) => {
  // console.log('BuildSetTable sensorToProps', state);
  return {
    // dvaData 属性名称 setting 指命名空间
    dvaData: state.setting,
  };
};

export default connect(sensorToProps)(SensorSet);
